package DAO;

import Entidad.Person;
import javax.persistence.EntityManager;
import javax.persistence.Query;

public class DAO_Person {
    
    public String create(Person persona, EntityManager em) {
        em.getTransaction().begin();
        try {
            em.persist(persona);
            em.getTransaction().commit();
            return "Succes";
        } catch (Exception e) {
            System.out.println(e);
            em.getTransaction().rollback();
            return "Fail";
        }
    }
    
    public String delete(String name, EntityManager em){
        em.getTransaction().begin();
        try{
            Query q = em.createQuery("DELETE FROM Person u WHERE u.Name = '" + name + "'");
            q.executeUpdate();
            em.getTransaction().commit();
            return "Succes";
        }catch(Exception e){
            System.out.println(e);
            em.getTransaction().rollback();
            return "Fail";
        }
    }
    
    public void update(Person antiguo, Person nuevo, EntityManager em){
        em.getTransaction().begin();
        try{
            Query q = em.createQuery("UPDATE Person s SET s.Name = '" +
                    nuevo.getName() + "', s.LastName = '"+ nuevo.getLastName() +
                    "', s.Picture = '"+ nuevo.getPicture() + "', s.Birthdate = '"
                    + nuevo.getBirthdate() +"', s.Birthplace = '"+nuevo.getBirthplace()+
                    "' WHERE s.nombre = '" + antiguo.getName() + "'");
            q.executeUpdate();
            em.getTransaction().commit();
        }catch(Exception e){
            System.out.println(e);
            em.getTransaction().rollback();
        }
    }
    
    public Person buscarPerson(String nombre, EntityManager em){
        try{
            Query q = em.createQuery("Select u from Person as u where u.Name = '"+ nombre +"'");
            return (Person)q.getSingleResult();
        }catch(Exception e){
            System.out.println(e);
            return null;
        }
    }
    
    public String tipo_persona(String nombre, EntityManager em){
        try{
            Query q = em.createQuery("Select PERSON_TYPE from Person as u where u.Name = '"+ nombre +"'");
            String rta = q.toString();
            return rta;
        }catch(Exception e){
            System.out.println(e);
            return null;
        }
    }
}
